package com.aso114.project.util;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.aso114.project.R;
import com.aso114.project.base.BaseApplication;
import com.aso114.project.bean.QuestionBaseBean;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.bean.questioncontentListBean;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.activity.LoginActivity;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


/**
 * username:Created by hsj on 2016/10/11 0011.
 * class：
 * 类描述：帮助工具类
 */

public class Helper {
    private static Toast toast;

    /**
     * 吐司
     *
     * @param msg 吐司显示信息
     */
    public static void showToast(String msg) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(BaseApplication.getInstance().context, msg, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * dpתpx
     *
     */
    public static int dip2px(Context ctx,float dpValue) {
        final float scale = ctx.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * @param fragmentActivity
     * @param f
     */
    public static void changeFragment(FragmentActivity fragmentActivity, int replaceLayoutId, Fragment f) {
        FragmentTransaction ft = fragmentActivity.getSupportFragmentManager().beginTransaction();
        ft.replace(replaceLayoutId, f, f.getClass().getSimpleName());
        ft.addToBackStack(null);
        ft.commitAllowingStateLoss();
    }

    /**
     * 获取版本code
     *
     * @throws Exception
     */
    public static int getVersionCode() {
        int version = 0;
        try {
            // ---get the package info---
            PackageManager pm = BaseApplication.getInstance().context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(BaseApplication.getInstance().context
                    .getPackageName(), 0);
            version = pi.versionCode;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return version;

    }

    /**
     * 获取版本Version
     *
     * @throws Exception
     */
    public static String getVersion() {
        String version = "";
        try {
            // ---get the package info---
            PackageManager pm = BaseApplication.getInstance().context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(BaseApplication.getInstance().context
                    .getPackageName(), 0);
            version = pi.versionName;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return version;

    }

    /**
     * @param txt 复制文本到剪切板
     */
    public static void copyToClipboard(String txt) {
        ClipboardManager cm = (ClipboardManager) BaseApplication.getInstance().getSystemService
                (Context.CLIPBOARD_SERVICE);
        cm.setText(txt);
    }

    /**
     * map按key排序,拼接成String
     *
     * @param map
     * @return
     */
    public static String getSign(Map<String, String> map) {
        String sign = "";
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> resultMap = sortMapByKey(map);
        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
            Log.i("yxp", entry.getKey() + " " + entry.getValue());

            sign += entry.getKey() + "=" + URLEncoder.encode(entry.getValue());

        }
        Log.i("yxp", sign.toLowerCase());
        Log.i("yxp", sign);
        return sign.toLowerCase();
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, String> sortMap = new TreeMap<String, String>(
                new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }

    /**
     * 比较器类
     */

    static class MapKeyComparator implements Comparator<String> {

        @Override
        public int compare(String str1, String str2) {

            return str1.compareTo(str2);
        }
    }


    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    public static void gotoLogin(boolean isSuccess) {
        if (!isSuccess) {
            LoginSP.getInstance().setToken("");
            Intent intent = new Intent(BaseApplication.getInstance(), LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BaseApplication.getInstance().startActivity(intent);
            return;
        }
    }

    public static void gotoLogin() {
        if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
            showToast("您还未登陆,请先登陆");
            Intent intent = new Intent(BaseApplication.getInstance(), LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BaseApplication.getInstance().startActivity(intent);
            return;
        }
    }


    /**
     * 字符串转换为Ascii
     */
    public static int stringToAscii(String value) {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]).append(",");
            } else {
                sbu.append((int) chars[i]);
            }
        }
        return Integer.valueOf(sbu.toString()) - 64;
    }

    /**
     * Ascii转换为字符串
     */
    public static String asciiToString(int num) {
        String value = String.valueOf(num + 64);
        StringBuffer sbu = new StringBuffer();
        String[] chars = value.split(",");
        for (int i = 0; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }

    /**
     * 判断两个数组是否相等
     */
    public static boolean equalList(List list1, List list2) {
        if (list1.size() != list2.size())
            return false;
        for (Object object : list1) {
            if (!list2.contains(object))
                return false;
        }
        return true;
    }

}
